package com.lujianfei.powersearch.ui.sort.touchhelper

import android.util.Log
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.Orientation
import com.lujianfei.powersearch.adapter.SortAdapter
import com.lujianfei.powersearch.base.MovableAdapter
import com.lujianfei.powersearch.ui.createOrUpdate.widget.imageviewedit.adapter.viewholder.ImageViewEditAdapterViewHolder

class SortDragTouchCallback(val sortAdapter: MovableAdapter<*,*>, val verticalMove:Boolean = true) : ItemTouchHelper.Callback() {
    override fun getMovementFlags(
        recyclerView: RecyclerView,
        viewHolder: RecyclerView.ViewHolder
    ): Int {
        val dragFlags = if (verticalMove) ItemTouchHelper.UP or ItemTouchHelper.DOWN else ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
        if (viewHolder is ImageViewEditAdapterViewHolder) {
            return makeMovementFlags(if (viewHolder.canMove()) dragFlags else 0, 0)
        }
        return makeMovementFlags(dragFlags, 0)
    }

    override fun isLongPressDragEnabled() = true

    override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
    }

    override fun onMove(
        recyclerView: RecyclerView,
        viewHolder: RecyclerView.ViewHolder,
        target: RecyclerView.ViewHolder
    ): Boolean {
        return sortAdapter.onItemMove(viewHolder.absoluteAdapterPosition, target.absoluteAdapterPosition)
    }

    override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
        if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
            sortAdapter.onSelectedChanged(viewHolder)
        }
        super.onSelectedChanged(viewHolder, actionState)
    }

    override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
        super.clearView(recyclerView, viewHolder)
        sortAdapter.clearView(viewHolder)
    }
}